package cat.joronya.supermanager.europeo;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
import cat.joronya.supermanager.europeo.R;
import cat.joronya.supermanager.europeo.service.SupermanagerIntent;

/**
 * Preference activity to handle user preferences.
 * @author pol
 *
 */
public class SupermanagerPreferenceActivity extends PreferenceActivity 
	implements OnSharedPreferenceChangeListener
{
	public static final String TAG = "supermanager";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		// Load the preferences from an XML resource
		addPreferencesFromResource(R.xml.preferences);
	}
	
	@Override
    protected void onResume() 
	{
        super.onResume();
        
        // Set up a listener whenever a key changes            
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
	}
	
	@Override
    protected void onPause() 
	{
        super.onPause();

        // Unregister the listener whenever a key changes            
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);    
    }

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) 
	{
		// recuperem el gestor d'alarmes
		AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		
		// recuperem dades pel login
		String username = sharedPreferences.getString(Supermanager.PREFS_USERNAME, null);
   		String password = sharedPreferences.getString(Supermanager.PREFS_PASSWORD, null);
   		
		// s'ha canviat el cron enabled?
		if( key.equals(Supermanager.PREFS_CRON_ENABLED) )
		{
			// supermanager sync intent
			SupermanagerIntent superIntent = 
				new SupermanagerIntent(SupermanagerIntent.ACTION_SYNC,
						Supermanager.Home.CONTENT_URI, this, null);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.username", username);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.password", password);
			superIntent.putExtra("cat.joronya.supermanager.europeo.fullupdate.shownotifications", false);
			
			// creem el pending intent
			PendingIntent newPending =  PendingIntent.getService(this, 0, superIntent, 0);
			
			// mirem si cal programar o desprogramar update
			if( sharedPreferences.getBoolean(key, false) )
			{
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): schedule refresh alarm");
				
				// cron hour
		   		String cronHour = sharedPreferences.getString(Supermanager.PREFS_CRON_HOUR, "07");
		   		
		   		// programem avui a l'hora establerta
				Calendar now = GregorianCalendar.getInstance();
				Calendar gc = new GregorianCalendar(now.get(Calendar.YEAR), 
						now.get(Calendar.MONTH), 
						now.get(Calendar.DAY_OF_MONTH), 
						Integer.parseInt(cronHour),
						0);
				
				// repetir l'alarma diariament, update diari
				alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
						gc.getTimeInMillis(), 1000*60*60*24, newPending);
				
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): refresh alarm scheduled daily");
			}
			else
			{
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): refresh alarm removed");
				
				// desprogramem l'alarma
				alarmManager.cancel(newPending);
			}
		}
		
		// s'ha canviat l'hora del cron?
		if( key.equals(Supermanager.PREFS_CRON_HOUR) )
		{
			// supermanager sync intent
			SupermanagerIntent superIntent = 
				new SupermanagerIntent(SupermanagerIntent.ACTION_SYNC,
						Supermanager.Home.CONTENT_URI, this, null);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.username", username);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.password", password);
			superIntent.putExtra("cat.joronya.supermanager.europeo.fullupdate.shownotifications", false);
			
			// creem el pending intent
			PendingIntent newPending =  PendingIntent.getService(this, 0, superIntent, 0);
			
			// primer desprogramem alarma existent
			Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): refresh alarm removed");
			alarmManager.cancel(newPending);
			
			// despres reprogramem l'alarma a la nova hora
			Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): schedule refresh alarm");
				
			// cron hour
	   		String cronHour = sharedPreferences.getString(Supermanager.PREFS_CRON_HOUR, "07");
		   		
	   		// programem avui a l'hora establerta
			Calendar now = GregorianCalendar.getInstance();
			Calendar gc = new GregorianCalendar(now.get(Calendar.YEAR), 
					now.get(Calendar.MONTH), 
					now.get(Calendar.DAY_OF_MONTH), 
					Integer.parseInt(cronHour),
					0);
				
			// repetir l'alarma diariament, update diari
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
					gc.getTimeInMillis(), 1000*60*60*24, newPending);
				
			Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): refresh alarm scheduled daily");
		}
		
		// enable/disable close changes notify
		if( key.equals(Supermanager.PREFS_DUETIME_NOTIFICATION_ENABLED)  )
		{
			// supermanager sync intent
			SupermanagerIntent superIntent = 
				new SupermanagerIntent(SupermanagerIntent.ACTION_VIEW,
						Supermanager.Home.CONTENT_URI, this, null);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.username", username);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.password", password);
			
			// creem el pending intent
			PendingIntent newPending =  PendingIntent.getService(this, 0, superIntent, 0);
			
			// mirem si cal programar o desprogramar notification
			if( sharedPreferences.getBoolean(key, false) )
			{
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): schedule notification alarm");
				
				// notification hour
		   		String notificationHour = sharedPreferences.getString(Supermanager.PREFS_DUETIME_NOTIFICATION_HOUR, "04");
		   		
		   		Cursor cursor = getContentResolver().query(
						Supermanager.Home.CONTENT_URI, 
						Supermanager.Home.PROJECTION, 
						Supermanager.Home.DUE_TIME+" > "+(System.currentTimeMillis()/1000), 
						null, 
						Supermanager.Home.DUE_TIME+" DESC");
				
				// hi ha alguna data? Hem arribat al moment de mostrar la notificacio que s'escaigui
				if( cursor.moveToFirst() )
				{
					// duetime - notificationHour
					long duetime = cursor.getInt(4);
					duetime -= (Integer.parseInt(notificationHour)*60*60);
					
					// programem l'alarma al duetime - hores abans
					alarmManager.set(AlarmManager.RTC_WAKEUP, duetime*1000, newPending);
					
					Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): notificatin alarm scheduled");
				}
			}
			else
			{
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): notification alarm removed");
				
				// desprogramem l'alarma
				alarmManager.cancel(newPending);
			}
		}
		
		// change previous hours befeore close changes to notify
		if( key.equals(Supermanager.PREFS_DUETIME_NOTIFICATION_HOUR)  )
		{
			// supermanager sync intent
			SupermanagerIntent superIntent = 
				new SupermanagerIntent(SupermanagerIntent.ACTION_VIEW,
						Supermanager.Home.CONTENT_URI, this, null);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.username", username);
			superIntent.putExtra("cat.joronya.supermanager.europeo.login.password", password);
			
			// creem el pending intent
			PendingIntent newPending =  PendingIntent.getService(this, 0, superIntent, 0);
			
			// primer cancelem antiga programacio
			Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): notification alarm change hour removed");
			alarmManager.cancel(newPending);

			// reprogramem alarma
			Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): reschedule notification alarm");
				
			// notification hour
		   	String notificationHour = sharedPreferences.getString(Supermanager.PREFS_DUETIME_NOTIFICATION_HOUR, "04");
		   		
		   	Cursor cursor = getContentResolver().query(
					Supermanager.Home.CONTENT_URI, 
					Supermanager.Home.PROJECTION, 
					Supermanager.Home.DUE_TIME+" > "+(System.currentTimeMillis()/1000), 
					null, 
					Supermanager.Home.DUE_TIME+" DESC");
				
			// hi ha alguna data? Hem arribat al moment de mostrar la notificacio que s'escaigui
			if( cursor.moveToFirst() )
			{
				// duetime - notificationHour
				long duetime = cursor.getInt(4);
				duetime -= (Integer.parseInt(notificationHour)*60*60);
				
				// programem l'alarma al duetime - hores abans
				alarmManager.set(AlarmManager.RTC_WAKEUP, duetime*1000, newPending);
				
				Log.d(TAG, "SupermanagerPreferenceActivity.onSharedPreferenceChanged(): notificatin alarm rescheduled");
			}
		}

	}
}
